package com.ruoyi.system.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

import com.ruoyi.common.config.AiPathConfig;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.detectUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.commons.lang3.builder.ToStringExclude;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.HistoryInfoMapper;
import com.ruoyi.system.domain.HistoryInfo;
import com.ruoyi.system.service.IHistoryInfoService;

/**
 * 历史信息Service业务层处理
 * 
 * @author YDB
 * @date 2022-04-05
 */
@Service
public class HistoryInfoServiceImpl implements IHistoryInfoService 
{
    @Autowired
    private HistoryInfoMapper historyInfoMapper;

    /**
     * 查询历史信息
     * 
     * @param historyInfoId 历史信息主键
     * @return 历史信息
     */
    @Override
    public HistoryInfo selectHistoryInfoByHistoryInfoId(Long historyInfoId)
    {
        return historyInfoMapper.selectHistoryInfoByHistoryInfoId(historyInfoId);
    }

    /**
     * 查询历史信息列表
     * 
     * @param historyInfo 历史信息
     * @return 历史信息
     */
    @Override
    public List<HistoryInfo> selectHistoryInfoList(HistoryInfo historyInfo)
    {
        return historyInfoMapper.selectHistoryInfoList(historyInfo);
    }

    /**
     * 新增历史信息
     * 
     * @param historyInfo 历史信息
     * @return 结果
     */
    @Override
    public int insertHistoryInfo(HistoryInfo historyInfo)
    {
        historyInfo.setCreateTime(DateUtils.getNowDate());
        return historyInfoMapper.insertHistoryInfo(historyInfo);
    }

    /**
     * 修改历史信息
     * 
     * @param historyInfo 历史信息
     * @return 结果
     */
    @Override
    public int updateHistoryInfo(HistoryInfo historyInfo)
    {
        return historyInfoMapper.updateHistoryInfo(historyInfo);
    }

    /**
     * 批量删除历史信息
     * 
     * @param historyInfoIds 需要删除的历史信息主键
     * @return 结果
     */
    @Override
    public int deleteHistoryInfoByHistoryInfoIds(Long[] historyInfoIds)
    {
        return historyInfoMapper.deleteHistoryInfoByHistoryInfoIds(historyInfoIds);
    }

    /**
     * 删除历史信息信息
     * 
     * @param historyInfoId 历史信息主键
     * @return 结果
     */
    @Override
    public int deleteHistoryInfoByHistoryInfoId(Long historyInfoId)
    {
        return historyInfoMapper.deleteHistoryInfoByHistoryInfoId(historyInfoId);
    }

    /**
     * 变化检测-算法调用
     */
    @Override
    public AjaxResult bhjc(List<Map<String,String>> data,Long UserId,String tUsername){
        // 上传文件路径
        String uploadPath = RuoYiConfig.getUploadPath();
        HistoryInfo historyInfo = new HistoryInfo();
        String s = "python  "+ AiPathConfig.getBhjcDemoPath()+"  --output_dir " +
                uploadPath +
                "  --image1  " +
                data.get(0).get("filePath").replace("/profile/upload",uploadPath) +
                "  --image2  " +
                data.get(1).get("filePath").replace("/profile/upload",uploadPath);
        historyInfo.setCreaterID(UserId);
        historyInfo.setCreateName(tUsername);
        historyInfo.setDetectType(Long.parseLong(data.get(0).get("typeFlag")));
        historyInfo.setCreateTime(new Date());
        historyInfo.setInputData(data.get(0).get("filePath")+","+data.get(1).get("filePath"));
        detectUtils.detect(s);
        String fileName="";
        try {
            fileName = FileUploadUtils.upload(uploadPath, detectUtils.getMultipartFile(new File(uploadPath+"/bhjc.png")));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("检测出错,请联系管理人员");
        }
        historyInfo.setDetectRes(fileName);
        historyInfoMapper.insertHistoryInfo(historyInfo);
        return AjaxResult.success(fileName);
    }

    /**
     * 目标检测-算法调用
     */
    @Override
    public AjaxResult mbjc(List<Map<String, String>> data, Long userId, String username){
        // 上传文件路径
        String uploadPath = RuoYiConfig.getUploadPath();
        HistoryInfo historyInfo = new HistoryInfo();
        String s = "python  "+AiPathConfig.getMbjcDemoPath()+"  --output_dir " +
                uploadPath +
                "  --image1  " +
                data.get(0).get("filePath").replace("/profile/upload",uploadPath);
        historyInfo.setCreaterID(userId);
        historyInfo.setCreateName(username);
        historyInfo.setDetectType(Long.parseLong(data.get(0).get("typeFlag")));
        historyInfo.setCreateTime(new Date());
        historyInfo.setInputData(data.get(0).get("filePath"));
        detectUtils.detect(s);
        String fileName="";
        try {
            fileName = FileUploadUtils.upload(uploadPath, detectUtils.getMultipartFile(new File(uploadPath+"/mbjc.png")));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("检测出错,请联系管理人员");
        }
        historyInfo.setDetectRes(fileName);
        historyInfoMapper.insertHistoryInfo(historyInfo);
        return AjaxResult.success(fileName);
    }

    /**
     * 目标提取-算法调用
     */
    @Override
    public AjaxResult mbtq(List<Map<String, String>> data, Long userId, String username){
        // 上传文件路径
        String uploadPath = RuoYiConfig.getUploadPath();
        HistoryInfo historyInfo = new HistoryInfo();
        String s = "python  "+AiPathConfig.getMbtqDemoPath()+"  --output_dir " +
                uploadPath +
                "  --image1  " +
                data.get(0).get("filePath").replace("/profile/upload",uploadPath);
        historyInfo.setCreaterID(userId);
        historyInfo.setCreateName(username);
        historyInfo.setDetectType(Long.parseLong(data.get(0).get("typeFlag")));
        historyInfo.setCreateTime(new Date());
        historyInfo.setInputData(data.get(0).get("filePath"));
        detectUtils.detect(s);
        String fileName="";
        try {
            fileName = FileUploadUtils.upload(uploadPath, detectUtils.getMultipartFile(new File(uploadPath+"/mbtq.png")));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("检测出错,请联系管理人员");
        }
        historyInfo.setDetectRes(fileName);
        historyInfoMapper.insertHistoryInfo(historyInfo);
        return AjaxResult.success(fileName);
    }

//    /**
//     * 地物分类-算法调用-动态模型-使用lab图
//     */
//    @Override
//    public AjaxResult dwfl(List<Map<String, String>> data, Long userId, String username){
//        // 上传文件路径
//        String uploadPath = RuoYiConfig.getUploadPath();
//        //默认删除上次识别的文件
//        FileUtils.deleteFile(uploadPath+"/dwfl.png");
//        HistoryInfo historyInfo = new HistoryInfo();
//        String s = "python  "+AiPathConfig.getDwflDemoPath()+"  --output_dir " + uploadPath;
//        historyInfo.setCreaterID(userId);
//        historyInfo.setCreateName(username);
//        historyInfo.setDetectType(Long.parseLong(data.get(0).get("typeFlag")));
//        historyInfo.setCreateTime(new Date());
//        historyInfo.setInputData(data.get(0).get("filePath"));
//        String LabFile=AiPathConfig.getDwflLab()+data.get(0).get("name").replace("jpg","png");
//        FileUtils.WriteStringToFile(data.get(0).get("filePath").replace("/profile/upload",uploadPath)+" "+LabFile,"C:/Users/YDB/Desktop/RJB-model/DWFL/data/test.txt");
//        detectUtils.detect(s);
//        String fileName="";
//        try {
//            fileName = FileUploadUtils.upload(uploadPath, detectUtils.getMultipartFile(new File(uploadPath+"/dwfl.png")));
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException("检测出错,请联系管理人员");
//        }
//        historyInfo.setDetectRes(fileName);
//        historyInfoMapper.insertHistoryInfo(historyInfo);
//        return AjaxResult.success(fileName);
//    }
    /**
     * 地物分类-算法调用-静态模型
     */
    @Override
    public AjaxResult dwfl(List<Map<String, String>> data, Long userId, String username){
        // 上传文件路径
        String uploadPath = RuoYiConfig.getUploadPath();
        HistoryInfo historyInfo = new HistoryInfo();
        String s = "python  "+AiPathConfig.getDwflDemoPath()+"  --output_dir " +
                uploadPath +
                "  --image1  " +
                data.get(0).get("filePath").replace("/profile/upload",uploadPath);
        historyInfo.setCreaterID(userId);
        historyInfo.setCreateName(username);
        historyInfo.setDetectType(Long.parseLong(data.get(0).get("typeFlag")));
        historyInfo.setCreateTime(new Date());
        historyInfo.setInputData(data.get(0).get("filePath"));
        detectUtils.detect(s);
        String fileName="";
        try {
            fileName = FileUploadUtils.upload(uploadPath, detectUtils.getMultipartFile(new File(uploadPath+"/dwfl.png")));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("检测出错,请联系管理人员");
        }
        historyInfo.setDetectRes(fileName);
        historyInfoMapper.insertHistoryInfo(historyInfo);
        return AjaxResult.success(fileName);
    }

    /**
     * 车辆检测-算法调用
     */
    public AjaxResult cljc(List<Map<String, String>> data, Long userId, String username){
        // 上传文件路径
        String uploadPath = RuoYiConfig.getUploadPath();
        HistoryInfo historyInfo = new HistoryInfo();
        String s = "python  "+AiPathConfig.getCljcDemoPath()+"  --output_dir " +
                uploadPath +
                "  --image1  " +
                data.get(0).get("filePath").replace("/profile/upload",uploadPath);
        detectUtils.detect(s);
        historyInfo.setCreaterID(userId);
        historyInfo.setCreateName(username);
        historyInfo.setDetectType(Long.parseLong(data.get(0).get("typeFlag")));
        historyInfo.setCreateTime(new Date());
        historyInfo.setInputData(data.get(0).get("filePath"));

        String fileName="";
        try {
            fileName = FileUploadUtils.upload(uploadPath, detectUtils.getMultipartFile(new File(uploadPath+"/cljc.png")));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("检测出错,请联系管理人员");
        }
        historyInfo.setDetectRes(fileName);
        historyInfoMapper.insertHistoryInfo(historyInfo);
        return AjaxResult.success(fileName);
    }

    /**
     * 语义分割-算法调用
     */
    @Override
    public AjaxResult yyfg(List<Map<String, String>> data, Long userId, String username){
        // 上传文件路径
        String uploadPath = RuoYiConfig.getUploadPath();
        HistoryInfo historyInfo = new HistoryInfo();
        String s = "python  "+AiPathConfig.getYyfgDemoPath()+
                "  --save_dir " +
                uploadPath +
                "  --image_path  " +
                data.get(0).get("filePath").replace("/profile/upload",uploadPath);
        historyInfo.setCreaterID(userId);
        historyInfo.setCreateName(username);
        historyInfo.setDetectType(Long.parseLong(data.get(0).get("typeFlag")));
        historyInfo.setCreateTime(new Date());
        historyInfo.setInputData(data.get(0).get("filePath"));
        detectUtils.detect(s);
        String fileName="";
        try {
            fileName = FileUploadUtils.upload(uploadPath, detectUtils.getMultipartFile(new File(uploadPath+"/yyfg.png")));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("检测出错,请联系管理人员");
        }
        historyInfo.setDetectRes(fileName);
        historyInfoMapper.insertHistoryInfo(historyInfo);
        return AjaxResult.success(fileName);
    }

    /**
     * 语义分割-算法调用
     */
    @Override
    public AjaxResult cjfl(List<Map<String, String>> data, Long userId, String username){
        // 上传文件路径
        String uploadPath = RuoYiConfig.getUploadPath();
        HistoryInfo historyInfo = new HistoryInfo();
        String s = "python  "+AiPathConfig.getCjflDemoPath()+"  --output_dir " +
                uploadPath +
                "  --image1  " +
                data.get(0).get("filePath").replace("/profile/upload",uploadPath);
        detectUtils.detect(s);
        historyInfo.setCreaterID(userId);
        historyInfo.setCreateName(username);
        historyInfo.setDetectType(Long.parseLong(data.get(0).get("typeFlag")));
        historyInfo.setCreateTime(new Date());
        historyInfo.setInputData(data.get(0).get("filePath"));

        String fileName="";
        try {
            fileName = FileUploadUtils.upload(uploadPath, detectUtils.getMultipartFile(new File(uploadPath+"/cjfl.png")));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("检测出错,请联系管理人员");
        }
        historyInfo.setDetectRes(fileName);
        historyInfoMapper.insertHistoryInfo(historyInfo);
        return AjaxResult.success(fileName);
    }

    /**
     * 获取检测类别统计数据
     */
    @Override
    public AjaxResult selectDetectTypeInfo() {
        Map<String,String> type=new HashMap<>();
        type.put("1","变化检测");type.put("2","目标提取");type.put("3","目标检测");type.put("4","地物分类");
        type.put("5","车辆检测");type.put("6","语义分割");type.put("7","场景分类");
        Map<String,Integer> info=new HashMap<>();
        List<HistoryInfo> historyInfos = historyInfoMapper.selectHistoryInfoList(new HistoryInfo());
        for (HistoryInfo historyInfo : historyInfos) {
            if(info.containsKey(type.get(historyInfo.getDetectType()+""))){
                Integer temp=info.get(type.get(historyInfo.getDetectType()+""))+1;
                info.put(type.get(historyInfo.getDetectType()+""),temp);
            }else {
                info.put(type.get(historyInfo.getDetectType()+""),1);
            }
        }
        return AjaxResult.success(info);
    }

    /**
     * 上周检测统计
     */
    @Override
    public AjaxResult selectDetectNum(){
        List<HistoryInfo> historyInfos = historyInfoMapper.selectHistoryInfoList(new HistoryInfo());
        List<Integer> info=Arrays.asList(0,0,0,0,0,0,0);
        //上周的今天
        LocalDate LastWeekToday = LocalDate.now().minusDays(7);
        //上周周一
        LocalDate d1 = LastWeekToday.with(TemporalAdjusters.previous( DayOfWeek.MONDAY));
        LocalDate d2 = d1.plusDays(1);
        LocalDate d3 = d1.plusDays(2);
        LocalDate d4 = d1.plusDays(3);
        LocalDate d5 = d1.plusDays(4);
        LocalDate d6 = d1.plusDays(5);
        //上周周日
        LocalDate d7 = d1.plusDays(6);
        //上上周周日
        LocalDate dd7=d1.minusDays(1);
        //本周周一
        LocalDate t1=d1.plusDays(7);
        for (HistoryInfo historyInfo : historyInfos) {
            LocalDate tempDate=DateUtils.dateToLocalDate(historyInfo.getCreateTime());
            if(DateUtils.localDateIsBefore(tempDate,d2) && DateUtils.localDateIsAfter(tempDate,dd7)){
                Integer tempSum = info.get(0)+1;
                info.set(0,tempSum);
            }else if(DateUtils.localDateIsBefore(tempDate,d3) && DateUtils.localDateIsAfter(tempDate,d1)){
                Integer tempSum = info.get(1)+1;
                info.set(1,tempSum);
            }else if(DateUtils.localDateIsBefore(tempDate,d4) && DateUtils.localDateIsAfter(tempDate,d2)){
                Integer tempSum = info.get(2)+1;
                info.set(2,tempSum);
            }else if(DateUtils.localDateIsBefore(tempDate,d5) && DateUtils.localDateIsAfter(tempDate,d3)){
                Integer tempSum = info.get(3)+1;
                info.set(3,tempSum);
            }else if(DateUtils.localDateIsBefore(tempDate,d6) && DateUtils.localDateIsAfter(tempDate,d4)){
                Integer tempSum = info.get(4)+1;
                info.set(4,tempSum);
            }else if(DateUtils.localDateIsBefore(tempDate,d7) && DateUtils.localDateIsAfter(tempDate,d5)){
                Integer tempSum = info.get(5)+1;
                info.set(5,tempSum);
            }else if(DateUtils.localDateIsBefore(tempDate,t1) && DateUtils.localDateIsAfter(tempDate,d6)){
                Integer tempSum = info.get(6)+1;
                info.set(6,tempSum);
            }
        }
        return AjaxResult.success(info);
    }

}
